<?php
    class Common{
        static function multiSort($array,$field,$type=1)
        {
            $array_sort=array();
            if($array)
            {
                foreach($array as $key=>$row)
                {
                    $array_sort[$key]=$row[$field];
                }
                if($type==1)
                    array_multisort($array_sort,SORT_DESC,$array);
                else 
                    array_multisort($array_sort,SORT_ASC,$array); 
            }    
            return  $array;     
        }  

        static function getHostUser($username){
            $is_mtop = true; 
            $path = $_SERVER["HTTP_HOST"];
            $arr_path = explode(".",$path);
            if(count($arr_path) ==3){
                $is_mtop = true;
                if(strpos($path, "mtop.vn")===false && strpos($path, "hayquadi.com")===false && strpos($path, "localhost")===false && strpos($path, "hayquadi.com")===false){
                    $is_mtop = false; 
                }
                if($is_mtop==true){
                    $host = "http://".$username.'.'.Yii::app()->params["domain_mtop"];
                }else{
                    $host = "http://".$_SERVER['HTTP_HOST']; 
                }
            }else{
                $host = "http://".$_SERVER['HTTP_HOST'];
            }
            return $host;
        }      
        // hàm lấy ảnh
        static function getImgError(){
            return Yii::app()->params['static_url'].'/images/farmvui52.png';
        }
        static function getImageDomain($nameImage, $folder, $date='', $type='',$domain=0){
            switch($domain){
                case 1: 
                    $urlImages = Yii::app()->params["url_mtop"].'/upload/';
                    break;
                case 2: 
                    $urlImages = Yii::app()->params["url_mtop"].'/upload/';
                    break;
                case 3: 
                    $urlImages = Yii::app()->params["url_mtop"].'/upload/';
                    break;
                default:
                    $urlImages = Yii::app()->params['urlImages'];
                    break;
            }
            if($type!='')
                $nameImage=$type.'_'.$nameImage;
            if($date!='')
                return $urlImages.$folder.'/'.date('Y', $date).'/'.date('md', $date).'/'.$nameImage;
            else
                return $urlImages.$folder.'/'.$nameImage;
        }
        static function getImage($nameImage, $folder, $date='', $type='')
        {  
            if($type!='')
                $nameImage=$type.'_'.$nameImage;
            if($date!='')
                return Yii::app()->params['urlImages_mtop'].$folder.'/'.date('Y', $date).'/'.date('md', $date).'/'.$nameImage;
            else
                return Yii::app()->params['urlImages_mtop'].$folder.'/'.$nameImage;
        }
        static function getImageKkt($nameImage, $folder, $date='', $type='')
        {  
            if($type!='')
                $nameImage=$type.'_'.$nameImage;
            if($date!='')
                return Yii::app()->params['urlImages_kkt'].$folder.'/'.date('Y', $date).'/'.date('md', $date).'/'.$nameImage;
            else
                return Yii::app()->params['urlImages_kkt'].$folder.'/'.$nameImage;
        }

        static function getRealIpAddr()
        {
            if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
            {
                $ip=$_SERVER['HTTP_CLIENT_IP'];
            }
            elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
            {
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            else
            {
                $ip=$_SERVER['REMOTE_ADDR'];
            }
            return $ip;
        }

        /**
        * put your comment there...
        *  
        * @param mixed $email
        */
        static function validateEmailSyntax($email) {
            $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // allowed characters for part before "at" character
            $domain = '([-a-z0-9]*[a-z0-9]+)'; // allowed characters for part after "at" character
            $regex = '^'.$atom.'+'. // One or more atom characters.
            '(\.'.$atom.'+)*'. // Followed by zero or more dot separated sets of one or more atom characters.
            '@'. // Followed by an "at" character.
            '('.$domain.'{1,63}\.)+'. // Followed by one or max 63 domain characters (dot separated).
            $domain.'{2,63}'. // Must be followed by one set consisting a period of two
            '$'; // or max 63 domain characters.
            if(eregi($regex,$email)) return true;
            else  return false;
        } //validate_email_syntax

        /* Hàm lấy introtext trong nội dung */
        static function getIntroText($str,$len,$more){
            if ($str=="" || $str==NULL) 
                return $str;
            if (is_array($str)) 
                return $str;
            $str = trim($str);
            if (strlen($str) <= $len) 
                return $str;
            $str = substr($str,0,$len);
            if ($str != "") 
            {
                if (!substr_count($str," ")) 
                {
                    if ($more) 
                        $str .= " ...";
                    return $str;
                }
                while(strlen($str) && ($str[strlen($str)-1] != " ")) 
                {
                    $str = substr($str,0,-1);
                }
                $str = substr($str,0,-1);
                if ($more) 
                    $str .= " ...";
            }
            return $str;
        }

        function generate_slug($string) {
            $string = Common::change($string);
            $string = preg_replace("/(^|&\S+;)|(<[^>]*>)/U", "", $string);
            $string = strtolower(preg_replace('/[\s\-]+/', '-', trim(preg_replace('/[^\w\s\-]/', '', $string))));
            $slug = preg_replace("/[^A-Za-z0-9\-]/", "", $string);
            return $slug;
        }

        function generate_slug_search($string) {
            $string = Common::change($string);
            $string = preg_replace("/(^|&\S+;)|(<[^>]*>)/U", "", $string);
            $string = strtolower(preg_replace('/[\s\-]+/', '_', trim(preg_replace('/[^\w\s\-]/', '', $string))));
            $slug = preg_replace("/[^A-Za-z0-9\_]/", "", $string);
            return $slug;
        }

        function generate_slug_filename($string) {
            $string = Common::change($string);
            $string = preg_replace("/(^|&\S+;)|(<[^>]*>)/U", "", $string);
            $string = strtolower(preg_replace('/[\s\-]+/', '_', trim(preg_replace('/[^\w\s\-]/', '', $string))));
            $slug = preg_replace("/[^A-Za-z0-9\_]/", "", $string);
            return $slug;
        }

        function change($text) {
            $chars = array("a", "A", "e", "E", "o", "O", "u", "U", "i", "I", "d", "D", "y", "Y");
            $uni[0] = array("á", "à", "ạ", "ả", "ã", "â", "ấ", "ầ", "ậ", "ẩ", "ẫ", "ă", "ắ", "ằ", "ặ", "ẵ", "ẳ", "� �");
            $uni[1] = array("Á", "À", "Ạ", "Ả", "Ã", "Â", "Ấ", "Ầ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ắ", "Ằ", "Ặ", "Ẵ", "Ẳ", "� �");
            $uni[2] = array("é", "è", "ẹ", "ẻ", "ẽ", "ê", "ế", "ề", "ệ", "ể", "ễ");
            $uni[3] = array("É", "È", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ế", "Ề", "Ệ", "Ể", "Ễ");
            $uni[4] = array("ó", "ò", "ọ", "ỏ", "õ", "ô", "ố", "ồ", "ộ", "ổ", "ỗ", "ơ", "ớ", "ờ", "ợ", "ỡ", "ở", "� �");
            $uni[5] = array("Ó", "Ò", "Ọ", "Ỏ", "Õ", "Ô", "Ố", "Ồ", "Ộ", "Ổ", "Ỗ", "Ơ", "Ớ", "Ờ", "Ợ", "Ỡ", "Ở", "� �");
            $uni[6] = array("ú", "ù", "ụ", "ủ", "ũ", "ư", "ứ", "ừ", "ự", "ử", "ữ");
            $uni[7] = array("Ú", "Ù", "Ụ", "Ủ", "Ũ", "Ư", "Ứ", "Ừ", "Ự", "Ử", "Ữ");
            $uni[8] = array("í", "ì", "ị", "ỉ", "ĩ");
            $uni[9] = array("Í", "Ì", "Ị", "Ỉ", "Ĩ");
            $uni[10] = array("đ");
            $uni[11] = array("Đ");
            $uni[12] = array("ý", "ỳ", "ỵ", "ỷ", "ỹ");
            $uni[13] = array("Ý", "Ỳ", "Ỵ", "Ỷ", "Ỹ");

            for ($i = 0; $i <= 13; $i++) {
                $text = str_replace($uni[$i], $chars[$i], $text);
            }
            return $text;
        }   

        function file_extension($filename)
        {
            return end(explode(".", $filename));
        }

        public function remove_duplicate($list_id)
        {
            $list_id = explode(",", $list_id);
            $new_id = array();
            foreach($list_id as $value){
                if(!in_array($value, $new_id)){
                    $new_id[] = $value;
                }
            }            
            $list_new_id = "";
            foreach($new_id as $value){
                $list_new_id .= $value.",";   
            }
            $list_new_id = rtrim($list_new_id, ",");
            return $list_new_id;
        }        

        public function removeSign($str) {
            $coDau = array ("à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ", "ì", "í", "ị", "ỉ", "ĩ", "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ", "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ", "ỳ", "ý", "ỵ", "ỷ", "ỹ", "đ", "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ", "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ", "Ì", "Í", "Ị", "Ỉ", "Ĩ", "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ợ", "Ở", "Ỡ", "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ", "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ", "Đ", "ê", "ù", "à" );

            $khongDau = array ("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "y", "y", "y", "y", "y", "d", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "I", "I", "I", "I", "I", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "Y", "Y", "Y", "Y", "Y", "D", "e", "u", "a" );
            return str_replace ( $coDau, $khongDau, $str );
        }                


        public function genDate($time)
        {        
            $curTime = time();
            $sub = $curTime - $time;
            if($sub < 60)
            {
                $date = $sub . " seconds ago";
            } 
            else if($sub >= 60 && $sub < 3600)
                {
                    $minutes = floor($sub / 60);
                    $date = $minutes . " minutes ago";
                } 
                else if($sub >= 3600 && $sub < 24 * 3600)
                    {
                        $hours = floor($sub / 3600);
                        $minutes = floor(($sub - ($hours * 3600)) / 60);  
                        $date = $hours . " hour " . $minutes . " minutes ago";
                    } 
                    else if($sub >= 24 * 3600 && $sub < 7 * 24 * 3600)
                        {        
                            $date = date("l", $time) . " at " . date("H:i", $time);
                        } 
                        else if($sub >= 7 * 24 * 3600 && $sub < 30 * 24 * 3600)
                            {        
                                $date = date("l", $time) . ", " . date("F", $time) . " " . date("d", $time) . " at " . date("H:i", $time);
                            } 
                            else 
                            {
                                $date = "At " . date("d-m-Y H:i:s");
            }        

            return $date;
        }

        static function CheckPassword($pwd)
        {        
            $error = "";
            if(strlen($pwd) < 6 ) {
                $error .= "<p>- Mật khẩu phải có ít nhất 6 ký tự</p>";            
            }

            if(strlen($pwd) > 15 ) {
                $error .= "<p>- Mật khẩu có nhiều nhất 15 ký tự</p>";            
            }        

            if(!preg_match("#[0-9]+#", $pwd) ) {
                //                $error .= "<p>- Mật khẩu phải có ít nhất 1 chữ số</p>";            
            }

            if(!preg_match("#[a-zA-Z]+#", $pwd) ) {
                //                $error .= "<p>- Mật khẩu phải có ít nhất 1 chữ viết</p>";            
            }

            if( !preg_match("#[A-Z]+#", $pwd) ) {
                //            $error .= "<p>- Mật khẩu phải có ít nhất 1 chữ viết hoa</p>";
            }

            if( !preg_match("#\W+#", $pwd) ) {
                //            $error .= "<p>- Mật khẩu phải có ít nhất 1 ký tự đặc biệt</p>";            
            }

            return $error;          
        }

        static function cleanQuery($string)
        {        
            if(empty($string)) return $string;
            $string = trim($string);

            $badWords = array(
            "/Select(.*)From/i"
            , "/Union(.*)Select/i"
            , "/Update(.*)Set/i"
            , "/Delete(.*)From/i"
            , "/Drop(.*)Table/i"
            , "/Insert(.*)Into/i"                
            , "/http/i"
            , "/--/i"
            );

            $string = preg_replace($badWords, "", $string);

            return $string;
        }        

        function detectMobile()
        {
            preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|sagem|sharp|sie-|smartphone|sonyericsson|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/si',$_SERVER['HTTP_USER_AGENT'],$match);
            $device=isset($match[1]) ? $match[1]:'';

            return $device;
        }

        public function serviceCode()
        {
            return array(
            "6022"=>"500"
            , "6122"=>"1000"
            , "6222"=>"2000"
            , "6322"=>"3000"
            , "6422"=>"4000"
            , "6522"=>"5000"
            , "6622"=>"10000"
            , "6722"=>"15000"
            );            
        }

        public function getDomain($sub_domain){
            $domain_default ='mtop.vn';
            $myhost = gethostname(); 
            $http_host = isset($_SERVER['HTTP_HOST'])? $_SERVER['HTTP_HOST']:$domain_default;
            $http_host = str_replace('www.','',$http_host);
            $http_host = str_replace('http://','',$http_host);
            $http_host = 'http://'.$http_host;
            $host_info = array();
            $host_info = parse_url($http_host);
            $domain = isset($host_info['host'])? $host_info['host']:$domain_default; 
            if(strpos($domain,$domain_default) ===false)
            {
                $myhost = $domain;  
            } 
            if($domain=='' || $domain=='mtop.vn'){
                return $domain;
            }     
            return str_replace($sub_domain.'.','',$domain);          
        }
        static function getImageError(){
            $img= Yii::app()->params['static_url'].'images/default_image.png'; 
            return $img;          
        }
        public function getSubDomain()
        {
            $path = $_SERVER['HTTP_HOST'];
            if (strpos($path,'.')!=FALSE)
            {
                $path = explode('.',$path);
                $path = $path[0];
            }
            else $path='';
            return $path;
        }

        static function getApp($user,$app_name)
        {
            return Yii::app()->params['urlImages'].'user/'.$user.'/'.$app_name;
        }

       
        /* định dạng giá tiền ngược */
        public function price_format($price){
            $price = str_replace(".", "", $price);    
            $price = str_replace(",", "", $price);    
            $price = str_replace(" ", "", $price);            
            return $price;
        }

        function detectFileExtension()
        {
            include 'Mobile_Detect.php';
            $detect = new Mobile_Detect();
            if($detect->isiOS()){
                $ext = "ipa";
            } elseif ($detect->isAndroidOS()){
                $ext = "apk";
            } elseif ($detect->isMobile()){
                $ext = "jar";
            } else{
                $ext = "jar";
            }

            return $ext;
        }

        function priceServiceCode($serviceCode)
        {
            $pattern_0 = "/^(\d)0(\d)(\d)$/si";
            $pattern_1 = "/^(\d)1(\d)(\d)$/si";
            $pattern_2 = "/^(\d)2(\d)(\d)$/si";
            $pattern_3 = "/^(\d)3(\d)(\d)$/si";
            $pattern_4 = "/^(\d)4(\d)(\d)$/si";
            $pattern_5 = "/^(\d)5(\d)(\d)$/si";
            $pattern_6 = "/^(\d)6(\d)(\d)$/si";        
            $pattern_7 = "/^(\d)7(\d)(\d)$/si";        

            $price = 0;
            if(preg_match($pattern_0, $serviceCode)){
                $price = 500;    
            } else if(preg_match($pattern_1, $serviceCode)){
                    $price = 1000;    
                } else if(preg_match($pattern_2, $serviceCode)){
                        $price = 2000;    
                    } else if(preg_match($pattern_3, $serviceCode)){
                            $price = 3000;    
                        } else if(preg_match($pattern_4, $serviceCode)){
                                $price = 4000;    
                            } else if(preg_match($pattern_5, $serviceCode)){
                                    $price = 5000;    
                                } else if(preg_match($pattern_6, $serviceCode)){
                                        $price = 10000;    
                                    } else if(preg_match($pattern_7, $serviceCode)){
                                            $price = 15000;    
                                        } 
                                        return $price;
        }

        public function checkTelco($mobile)
        {        
            $first = substr($mobile, 0, 1);
            if($first=="0"){
                $mobile = substr($mobile, 1, strlen($mobile) - 1);
            } else if($first="8"){
                    $mobile = substr($mobile, 2, strlen($mobile) - 2);
                }

                $mobile = "84" . $mobile;

            $patternViettel = "/^84(9[678]|16[2-9])[\d]{7}/";
            $patternMobi = "/^84(9[03]|12[01268])[\d]{7}/";
            $patternVina = "/^84(9[14]|12[34579])[\d]{7}/";
            $patternVnmobile = "/^84(9[2]|18[86])[\d]{7}/";
            $patternBeeline = "/^84(9[9]|19[9])[\d]{7}/";

            if(preg_match($patternViettel, $mobile)){
                $telco = "1";    
            } else if(preg_match($patternMobi, $mobile)){
                    $telco = "2";
                } else if(preg_match($patternVina, $mobile)){
                        $telco = "3";
                    } else if(preg_match($patternVnmobile, $mobile)){
                            $telco = "4";
                        } else if(preg_match($patternBeeline, $mobile)){
                                $telco = "5";
                            } else {
                                $telco = "0";
            }

            return $telco;    
        }

        /* định dạng số */
        public function format_price($price){
            $number = number_format($price,1,",","."); //Vietnamese format with decimals by a coma
            if(strrchr($number,",")==",0") return str_replace(",0","",$number);
            else return $number;
        }

        public function genPass($password)
        {
            return md5(md5($password) . "mtop_wap_content2012#$%^");
        }

        public function cleanFileName($string) {        
            $string = Common::change($string);        
            $string = preg_replace("/(^|&\S+;)|(<[^>]*>)/U", "", $string);
            $string = trim(preg_replace('/[^\w\s\(.)\-]/', '', $string));        
            $string = strtolower(preg_replace('/[\s\-]+/', '_', $string));    
            $string = preg_replace("/[^A-Za-z0-9\(.)\_]/", "", $string);     
            $string = str_replace("small","s_mall",$string);
            $string = str_replace("medium","m_deium",$string);   
            return $string;
        }

        public function genRefCode($id){
            return md5(md5($id) . "CunKIEmTieN$#$@$%");
        }

        public function genFilenameApp($type)
        {
            $agent = $_SERVER['HTTP_USER_AGENT'];
            $file = array();
            if($type==1){
                $filename = "MyGame";
            } else if($type==2){
                    $filename = "mSexy";
                } else if($type==3){
                        $filename = "mShow";
                    } else if($type==4){
                            $filename = "mStyle";
                        } else if($type==6){
                                $filename = "sms_kute";
                            } else if($type==7){
                                    $filename = "sms_kute_tet";
                                } else {
                                    $filename = "";
            }

            if (preg_match('/midp|Mobile|IEMobile|Fennec|Opera Mini|Opera Mobi|BlackBerry/si',$agent))
            {
                if(preg_match('/BlackBerry/si', $agent))
                {
                    $filename .= "_bb";
                }
            }

            return $filename;
        }

        public function encodeHex($id)
        {
            $id = intval($id);    
            $str = dechex($id + 27111986);        
            $subStr = substr(dechex($id + 26101984), -5); //last three characters        
            $str = $str . $subStr;

            return $str;
        }

        public function decodeHex($code)
        {
            $str = substr($code, 0, strlen($code) - 5);            
            $id = hexdec($str) - 27111986;        
            return intval($id);
        }

        public function buildRateServiceCode($rate, $total_money)
        {
            $total_money = intval($total_money);

            $rate_return = 0;
            if(isset($rate[$total_money])){
                $rate_return = $rate[$total_money];
            } else {
                $rate[$total_money] = 0;            
                ksort($rate);            
                $keys = array_keys($rate);            
                $current_key_index = array_search($total_money, $keys);            
                if(isset($keys[$current_key_index - 1])) {
                    $key = $keys[$current_key_index - 1];
                    $rate_return = $rate[$key];
                }            
            }        
            return $rate_return;            
        }

        public function buildRateCard($rate, $total_money)
        {
            $total_money = intval($total_money);

            $rate_return = 0;
            if(isset($rate[$total_money])){
                $rate_return = $rate[$total_money];
            } else {
                $rate[$total_money] = 0;
                ksort($rate);
                $keys = array_keys($rate);
                $current_key_index = array_search($total_money, $keys);
                if(isset($keys[$current_key_index - 1])) {
                    $key = $keys[$current_key_index - 1];
                    $rate_return = $rate[$key];
                }            
            }        
            return $rate_return;            
        }

        public function buildRateUser($rows, $total_money)
        {        
            $rate = array();        
            $rate["issue_rate_of_user"] = 0;
            $rate["issue_rate_of_mtop"] = 0;
            $rate["issue_rate_of_producer"] = 0;
            $rate["rate_of_user"] = 0;
            $rate["rate_of_mtop"] = 0;
            $rate["rate_of_producer"] = 0;
            if(!empty($rows)){            
                if($total_money < $rows["issue_price"]){                
                    $rate["issue_rate_of_user"] = $rows["issue_rate_of_user_min"];
                    $rate["issue_rate_of_mtop"] = $rows["issue_rate_of_mtop_min"];
                    $rate["issue_rate_of_producer"] = $rows["issue_rate_of_producer_min"];    
                } else {
                    $rate["issue_rate_of_user"] = $rows["issue_rate_of_user_max"];
                    $rate["issue_rate_of_mtop"] = $rows["issue_rate_of_mtop_max"];
                    $rate["issue_rate_of_producer"] = $rows["issue_rate_of_producer_max"];
                }

                if($total_money < $rows["price"]){
                    $rate["rate_of_user"] = $rows["rate_of_user_min"];
                    $rate["rate_of_mtop"] = $rows["rate_of_mtop_min"];
                    $rate["rate_of_producer"] = 0;
                } else {
                    $rate["rate_of_user"] = $rows["rate_of_user_max"];
                    $rate["rate_of_mtop"] = $rows["rate_of_mtop_max"];
                    $rate["rate_of_producer"] = 0;
                }
            }
            return $rate;
        }

        public function parseBBCode($str)
        {
            $pattern[0] = "/\[color=(.*?)\]/si";
            $replace[0] = "<span style='color:$1'>";
            $pattern[1] = "/\[\/color\]/si";
            $replace[1] = " </span>";

            $pattern[2] = "/\[background=(.*?)\]/si";
            $replace[2] = "<span style='background-color:$1'>";
            $pattern[3] = "/\[\/background\]/si";
            $replace[3] = " </span>";

            $pattern[4] = "/\[b\]/si";
            $replace[4] = "<strong>";
            $pattern[5] = "/\[\/b\]/si";
            $replace[5] = " </strong>";

            $pattern[6] = "/\[u\]/si";
            $replace[6] = "<u>";
            $pattern[7] = "/\[\/u\]/si";
            $replace[7] = " </u>";

            $pattern[8] = "/\[i\]/si";
            $replace[8] = " <i>";
            $pattern[9] = "/\[\/i\]/si";
            $replace[9] = " </i>";

            $pattern[10] = "/((http|https|ftp):\/\/(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)/si";
            $replace[10] = '<a href="$1" target="_blank">$2://$3</a>';
            $str = preg_replace($pattern, $replace, $str);

            $symbol = array(
            0=>':(('
            , 1=>':('     
            , 2=>':))'     
            , 3=>'/:)'     
            , 4=>':)]'     
            , 5=>'&lt;):)'     
            , 6=>'&gt;:)'     
            , 7=>':)'
            , 8=>'&gt;:D&lt;'
            , 9=>':D'
            , 10=>';;)'
            , 11=>';)'
            , 12=>'#:-S'
            , 13=>':-S'
            , 14=>'&gt;:P'
            , 15=>':P'
            , 16=>':-/'
            , 17=>':x'
            , 18=>':"&gt;'
            , 19=>'=(('
            , 20=>':-SS'
            , 21=>'&lt;:-P'
            , 22=>':-bd'
            , 23=>'^#(^'
            , 24=>':-*'
            , 25=>':-O'
            , 26=>'B-)'
            , 27=>':&gt;'
            , 28=>'~X('
            , 29=>'X('
            , 30=>':|'
            , 31=>'=))'
            , 32=>'O:-)'
            , 33=>':-B'
            , 34=>'=;'
            , 35=>':-c'
            , 36=>':-h'
            , 37=>':-t'
            , 38=>'8-&gt;'
            , 39=>'I-)'
            , 40=>'8-|'
            , 41=>'L-)'
            , 42=>':-&'
            , 43=>':-$'
            , 44=>'[-('
            , 45=>':O)'
            , 46=>'8-}'
            , 47=>'(:|'
            , 48=>'=P~'
            , 49=>':-?'
            , 50=>'#-o'
            , 51=>'=D&gt;'
            , 52=>'@-)'
            , 53=>':^o'
            , 54=>':-w'
            , 55=>':-&lt;'
            , 56=>'X_X'
            , 57=>':!!'
            , 58=>'\m/'
            , 59=>':-q'
            , 60=>':ar!'
            );    

            $icon = array(
            0=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/20.gif">'
            , 1=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/2.gif">'                 
            , 2=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/21.gif">'                 
            , 3=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/23.gif">'                 
            , 4=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/100.gif">'                 
            , 5=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/48.gif">'                 
            , 6=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/19.gif">'                 
            , 7=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/1.gif">'                 
            , 8=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/6.gif">'                 
            , 9=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/4.gif">'                 
            , 10=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/5.gif">'                 
            , 11=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/3.gif">'                 
            , 12=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/18.gif">'                 
            , 13=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/17.gif">'                 
            , 14=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/47.gif">'                 
            , 15=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/10.gif">'                 
            , 16=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/7.gif">'                 
            , 17=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/8.gif">'                 
            , 18=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/9.gif">'                 
            , 19=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/12.gif">'                 
            , 20=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/42.gif">'                 
            , 21=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/36.gif">'                 
            , 22=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/113.gif">'                 
            , 23=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/114.gif">'
            , 24=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/11.gif">'                 
            , 25=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/13.gif">'                 
            , 26=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/16.gif">'                 
            , 27=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/15.gif">'                 
            , 28=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/102.gif">'
            , 29=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/14.gif">'                 
            , 30=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/22.gif">'                 
            , 31=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/24.gif">'                 
            , 32=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/25.gif">'                 
            , 33=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/26.gif">'                 
            , 34=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/27.gif">'                 
            , 35=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/101.gif">'                 
            , 36=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/103.gif">'                 
            , 37=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/104.gif">'                 
            , 38=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/105.gif">'                 
            , 39=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/28.gif">'                 
            , 40=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/29.gif">'                 
            , 41=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/30.gif">'                 
            , 42=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/31.gif">'                 
            , 43=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/32.gif">'                 
            , 44=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/33.gif">'                 
            , 45=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/34.gif">'                 
            , 46=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/35.gif">'                 
            , 47=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/37.gif">'                 
            , 48=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/38.gif">'                 
            , 49=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/39.gif">'                 
            , 50=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/40.gif">'                 
            , 51=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/41.gif">'                 
            , 52=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/43.gif">'                 
            , 53=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/44.gif">'                 
            , 54=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/45.gif">'                 
            , 55=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/46.gif">'                 
            , 56=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/109.gif">'                 
            , 57=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/110.gif">'                 
            , 58=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/111.gif">'                 
            , 59=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/112.gif">'                 
            , 60=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/pirate_2.gif">'                                                  
            );
            $str = str_replace($symbol, $icon, $str);
            return $str;
        }

        public function bbcode_format($str){
            // Convert all special HTML characters into entities to display literally
            $str = strip_tags($str, "<strong><em><span><blockquote><p><pre><a><img>");
            // The array of regex patterns to look for
            $format_search =  array(
            '#\[b\](.*?)\[/b\]#is', // Bold ([b]text[/b]
            '#\[i\](.*?)\[/i\]#is', // Italics ([i]text[/i]
            '#\[u\](.*?)\[/u\]#is', // Underline ([u]text[/u])
            '#\[s\](.*?)\[/s\]#is', // Strikethrough ([s]text[/s])
            '#\[quote\](.*?)\[/quote\]#is', // Quote ([quote]text[/quote])
            '#\[code\](.*?)\[/code\]#is', // Monospaced code [code]text[/code])
            '#\[size=([1-9]|1[0-9]|20)\](.*?)\[/size\]#is', // Font size 1-20px [size=20]text[/size])
            '#\[color=\#?([A-F0-9]{3}|[A-F0-9]{6})\](.*?)\[/color\]#is', // Font color ([color=#00F]text[/color])
            '#\[url=((?:ftp|https?)://.*?)\](.*?)\[/url\]#i', // Hyperlink with descriptive text ([url=http://url]text[/url])
            '#\[url\]((?:ftp|https?)://.*?)\[/url\]#i', // Hyperlink ([url]http://url[/url])
            '#\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]#i' // Image ([img]http://url_to_image[/img])
            );
            // The matching array of strings to replace matches with
            $format_replace = array(
            '<strong>$1</strong>',
            '<em>$1</em>',
            '<span style="text-decoration: underline;">$1</span>',
            '<span style="text-decoration: line-through;">$1</span>',
            '<blockquote class="clearfix"><p>$1</p><span class="absolute"></span></blockquote>',
            '<pre>$1</'.'pre>',
            '<span style="font-size: $1px;">$2</span>',
            '<span style="color: #$1;">$2</span>',
            '<a href="$1">$2</a>',
            '<a href="$1">$1</a>',
            '<img src="$1" alt="" />'
            );
            // Perform the actual conversion
            $str = preg_replace($format_search, $format_replace, $str);

            $symbol = array(
            0=>':(('
            , 1=>':('     
            , 2=>':))'     
            , 3=>'/:)'     
            , 4=>':)]'     
            , 5=>'&lt;):)'     
            , 6=>'&gt;:)'     
            , 7=>':)'
            , 8=>'&gt;:D&lt;'
            , 9=>':D'
            , 10=>';;)'
            , 11=>';)'
            , 12=>'#:-S'
            , 13=>':-S'
            , 14=>'&gt;:P'
            , 15=>':P'
            , 16=>':-/'
            , 17=>':x'
            , 18=>':"&gt;'
            , 19=>'=(('
            , 20=>':-SS'
            , 21=>'&lt;:-P'
            , 22=>':-bd'
            , 23=>'^#(^'
            , 24=>':-*'
            , 25=>':-O'
            , 26=>'B-)'
            , 27=>':&gt;'
            , 28=>'~X('
            , 29=>'X('
            , 30=>':|'
            , 31=>'=))'
            , 32=>'O:-)'
            , 33=>':-B'
            , 34=>'=;'
            , 35=>':-c'
            , 36=>':-h'
            , 37=>':-t'
            , 38=>'8-&gt;'
            , 39=>'I-)'
            , 40=>'8-|'
            , 41=>'L-)'
            , 42=>':-&'
            , 43=>':-$'
            , 44=>'[-('
            , 45=>':O)'
            , 46=>'8-}'
            , 47=>'(:|'
            , 48=>'=P~'
            , 49=>':-?'
            , 50=>'#-o'
            , 51=>'=D&gt;'
            , 52=>'@-)'
            , 53=>':^o'
            , 54=>':-w'
            , 55=>':-&lt;'
            , 56=>'X_X'
            , 57=>':!!'
            , 58=>'\m/'
            , 59=>':-q'
            , 60=>':ar!'
            );    

            $icon = array(
            0=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/20.gif">'
            , 1=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/2.gif">'                 
            , 2=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/21.gif">'                 
            , 3=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/23.gif">'                 
            , 4=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/100.gif">'                 
            , 5=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/48.gif">'                 
            , 6=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/19.gif">'                 
            , 7=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/1.gif">'                 
            , 8=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/6.gif">'                 
            , 9=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/4.gif">'                 
            , 10=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/5.gif">'                 
            , 11=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/3.gif">'                 
            , 12=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/18.gif">'                 
            , 13=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/17.gif">'                 
            , 14=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/47.gif">'                 
            , 15=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/10.gif">'                 
            , 16=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/7.gif">'                 
            , 17=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/8.gif">'                 
            , 18=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/9.gif">'                 
            , 19=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/12.gif">'                 
            , 20=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/42.gif">'                 
            , 21=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/36.gif">'                 
            , 22=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/113.gif">'                 
            , 23=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/114.gif">'
            , 24=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/11.gif">'                 
            , 25=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/13.gif">'                 
            , 26=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/16.gif">'                 
            , 27=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/15.gif">'                 
            , 28=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/102.gif">'
            , 29=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/14.gif">'                 
            , 30=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/22.gif">'                 
            , 31=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/24.gif">'                 
            , 32=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/25.gif">'                 
            , 33=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/26.gif">'                 
            , 34=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/27.gif">'                 
            , 35=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/101.gif">'                 
            , 36=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/103.gif">'                 
            , 37=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/104.gif">'                 
            , 38=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/105.gif">'                 
            , 39=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/28.gif">'                 
            , 40=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/29.gif">'                 
            , 41=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/30.gif">'                 
            , 42=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/31.gif">'                 
            , 43=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/32.gif">'                 
            , 44=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/33.gif">'                 
            , 45=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/34.gif">'                 
            , 46=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/35.gif">'                 
            , 47=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/37.gif">'                 
            , 48=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/38.gif">'                 
            , 49=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/39.gif">'                 
            , 50=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/40.gif">'                 
            , 51=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/41.gif">'                 
            , 52=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/43.gif">'                 
            , 53=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/44.gif">'                 
            , 54=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/45.gif">'                 
            , 55=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/46.gif">'                 
            , 56=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/109.gif">'                 
            , 57=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/110.gif">'                 
            , 58=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/111.gif">'                 
            , 59=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/112.gif">'                 
            , 60=>'<img border="0" src="' . Yii::app()->params["static_url"] . 'images/emotions/pirate_2.gif">'                                                  
            );
            $str = str_replace($symbol, $icon, $str);

            // Convert line breaks in the <br /> tag
            $str = nl2br($str);
            return $str;
        }      

        public function online($location)
        {
            $rip = Common::getRealIpAddr();
            $sd = time();
            $count = 1;
            $maxu = 1;

            $file1 = $location . "online.log";
            $lines = file($file1);
            $line2 = "";

            foreach ($lines as $line_num => $line)
            {
                if($line_num == 0){
                    $maxu = $line;
                } else {
                    $fp = strpos($line,'****');
                    $nam = substr($line,0,$fp);
                    $sp = strpos($line,'++++');
                    $val = substr($line,$fp+4,$sp-($fp+4));
                    $diff = $sd-$val;

                    if($diff < 300 && $nam != $rip)
                    {
                        $count = $count+1;
                        $line2 = $line2.$line;
                    }
                }
            }

            $my = $rip . "****" . $sd . "++++\n";
            if($count > $maxu)
                $maxu = $count;

            $open1 = fopen($file1, "w");
            fwrite($open1, "$maxu\n");
            fwrite($open1, "$line2");
            fwrite($open1, "$my");
            fclose($open1);
            $count = $count;
            $maxu = $maxu + 200;

            return $count;
        }

        public function today($location)
        {
            $file_count = fopen($location . "count.txt", "rb");
            $data = '';
            while (!feof($file_count)) $data .= fread($file_count, 4096);
            fclose($file_count);
            @list($today, $yesterday, $total, $date, $days) = split("%", $data);
            return $today;
        }

        public function yesterday($location)
        {
            $file_count = fopen($location . "count.txt", "rb");
            $data = '';
            while (!feof($file_count)) $data .= fread($file_count, 4096);
            fclose($file_count);
            @list($today, $yesterday, $total, $date, $days) = split("%", $data);
            return $yesterday;
        }

        public function total($location)
        {
            $file_count = fopen($location . "count.txt", "rb");
            $data = "";
            while(!feof($file_count)) $data .= fread($file_count, 4096);
            fclose($file_count);
            @list($today, $yesterday, $total, $date, $days) = split("%", $data);
            return $total;
        }

        public function avg($location)
        {
            $file_count = fopen($location . "count.txt", "rb");
            $data = '';
            while (!feof($file_count)) $data .= fread($file_count, 4096);
            fclose($file_count);
            list($today, $yesterday, $total, $date, $days) = split("%", $data);
            return ceil($total/$days);
        }

        public function genToken($partner, $type)
        {            
            $token = md5(md5($partner) . "tokenMToP2013" . $type);
            return $token;    
        }

        public function buildGameVanKiem($file_game, $location_user, $file_name, $username)
        {
            $result = @copy($file_game, $location_user . $file_name . ".jar"); 
            $file_jad = "";
            $file_jad .= "Manifest-Version: 1.0.0\n";
            $file_jad .= "MIDlet-1: SwordOL, /icon.png, GameApp\n";
            $file_jad .= "MIDlet-Icon: /icon.png\n";
            $file_jad .= "MicroEdition-Configuration: CLDC-1.0\n";
            $file_jad .= "MIDlet-Version: 2.01\n";
            $file_jad .= "MIDlet-Name: SwordOL\n";
            $file_jad .= "MIDlet-Vendor: 掌上世界 \n";
            $file_jad .= "MicroEdition-Profile: MIDP-2.0\n";
            $file_jad .= "Nokia-MIDlet-App-Orientation: portrait\n";
            $file_jad .= "Nokia-MIDlet-On-Screen-Keypad: no\n";
            $file_jad .= "MIDlet-Jar-URL: " . $file_name . ".jar\n";
            $file_jad .= "MIDlet-Jar-Size: " . @filesize($location_user . $file_name . ".jar") . "\n";
            $fp = @fopen($location_user . $file_name . ".jad", "w");
            @fwrite($fp, $file_jad);                    
            @fclose($fp);

            if($result){
                return "Build game file " . $file_name . " thanh cong cho user " . $username . "\n";    
            } else {
                return "Khong build duoc game file " . $file_name . " cho user " . $username . "\n";    
            }            
        }

        public function cUrlHeader($url)
        {
            $curl_connection = curl_init($url);

            curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($curl_connection, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
            curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

            $result = curl_exec($curl_connection);            

            curl_close($curl_connection);                                       
            return $result;                
        }

        public function cUrl($url)
        {
            $curl_connection = curl_init($url);

            curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

            $result = curl_exec($curl_connection);            

            curl_close($curl_connection);                                       
            return $result;                
        } 

        public function buildSmobi($cpCode)
        {
            $post = array(
            "user"=>"mtop"
            , "pass"=>"kgl56hkoyijfbn134-!98r4r"
            , "gameId"=>"CT"
            , "cpName"=>"mtop" . $cpCode
            , "cpCode"=>$cpCode 
            );

            $curl_connection = curl_init('https://Smobi.vn/Store/CpRequest.ashx?action=build');

            //set options
            curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
            //            curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

            //set data to be posted
            curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post);

            //perform our request
            $result = curl_exec($curl_connection);            
            $result = urldecode($result);
            parse_str($result, $data);            

            curl_close($curl_connection);
            return $data["build"];
        }

        public function download($fnt, $fn, $p)
        {
            $dir_path = getcwd()."/upload/";                

            //lấy tên file cần download từ URL
            $fileNameTrue = $fnt;
            $fileName = $fn;
            $filePath = $p;
            $upload_dir = $dir_path . $filePath;

            //thực hiện quá trình kiểm tra
            if (!is_file($upload_dir.$fileName) || !is_readable($upload_dir.$fileName) ) 
            {
                echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                echo "Tên file không hợp lệ hoặc file ko tồn tại";
                exit(-1);
            }

            //mở file để đọc với chế độ nhị phân (binary)
            $fp = fopen($upload_dir.$fileName, "rb");

            //gởi header đến cho browser
            header('Content-type: application/octet-stream');
            header('Content-disposition: attachment; filename="' . $fileNameTrue . '"');
            header('Content-length: ' . filesize($upload_dir . $fileName));

            //đọc file và trả dữ liệu về cho browser
            fpassthru($fp);
            fclose($fp);
        }

        public function EncodeTeamobi($id)
        {
            $codes = array(0=>'A', 1=>'B', 2=>'C', 3=>'D', 4=>'E', 5=>'F', 6=>'G', 7=>'H', 8=>'I', 9=>'J', 10=>'K', 11=>'L', 12=>'M', 13=>'N', 14=>'O', 15=>'P', 16=>'Q', 17=>'R', 18=>'S', 19=>'T', 20=>'U', 21=>'V', 22=>'W', 23=>'X', 24=>'Y', 25=>'Z', 26=>'a', 27=>'b', 28=>'c', 29=>'d', 30=>'e', 31=>'f', 32=>'g', 33=>'h', 34=>'i', 35=>'j', 36=>'k', 37=>'l', 38=>'m', 39=>'n', 40=>'o', 41=>'p', 42=>'q', 43=>'r', 44=>'s', 45=>'t', 46=>'u', 47=>'v', 48=>'w', 49=>'x', 50=>'y', 51=>'z');

            if($id < 52){
                $code = $codes[$id];
            } else if($id >= 52 && $id < 52 * 52){
                    $hc = floor($id / 52);
                    $hdv = $id - 52 * $hc;

                    $hc = $codes[$hc];
                    $hdv = $codes[$hdv];

                    $code = $hc . $hdv;      
                } else if($id >= 52 * 52 && $id < 52 * 52 * 52){
                        $ht = floor($id / (52 * 52));
                        $tg = $id  - $ht * 52 * 52;
                        $hc = floor($tg / 52);
                        $hdv = $tg  - $hc * 52;

                        $ht = $codes[$ht];
                        $hc = $codes[$hc];
                        $hdv = $codes[$hdv];    

                        $code = $ht . $hc . $hdv;
                    } else {
                        $code = "";
            }
            return $code;
        }

        public function DecodeTeamobi($code)
        {
            $codes = array(0=>'A', 1=>'B', 2=>'C', 3=>'D', 4=>'E', 5=>'F', 6=>'G', 7=>'H', 8=>'I', 9=>'J', 10=>'K', 11=>'L', 12=>'M', 13=>'N', 14=>'O', 15=>'P', 16=>'Q', 17=>'R', 18=>'S', 19=>'T', 20=>'U', 21=>'V', 22=>'W', 23=>'X', 24=>'Y', 25=>'Z', 26=>'a', 27=>'b', 28=>'c', 29=>'d', 30=>'e', 31=>'f', 32=>'g', 33=>'h', 34=>'i', 35=>'j', 36=>'k', 37=>'l', 38=>'m', 39=>'n', 40=>'o', 41=>'p', 42=>'q', 43=>'r', 44=>'s', 45=>'t', 46=>'u', 47=>'v', 48=>'w', 49=>'x', 50=>'y', 51=>'z');
            if(strlen($code)==1){
                $id = array_search($code, $codes);    
            } else if(strlen($code)==2){
                    $hc = substr($code, 0, 1);    
                    $hdv = substr($code, 1, 1);    

                    $id = array_search($hc, $codes) * 52 + array_search($hdv, $codes);
                } else if(strlen($code)==3){
                        $ht = substr($code, 0, 1);    
                        $hc = substr($code, 1, 1);    
                        $hdv = substr($code, 2, 1);

                        $id = array_search($ht, $codes) * 52 * 52 + array_search($hc, $codes) * 52 + array_search($hdv, $codes);    
                    } else {
                        $id = 0;
            }

            return $id;
        }

       




        
        function generate_slug_register($string) {        
            $string = Common::change($string);
            $string = preg_replace("/(^|&\S+;)|(<[^>]*>)/U","",$string);
            $string = strtolower(preg_replace('/[\s\-]+/','',trim(preg_replace('/[^\w\s\-]/','',$string))));
            $slug = preg_replace("/[^A-Za-z0-9\-]/","",$string);
            return $slug;
        }
        public function getCurrentUrl(){
            $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
            if ($_SERVER["SERVER_PORT"] != "80")
            {
                $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
            } 
            else 
            {
                $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
            }
            return $pageURL;
        }

        public function callUrlAction($url='',$params=array()){
            //create cURL connection
            $curl_connection = curl_init($url);
            //set options
            curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($curl_connection, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
            //set data to be posted
            curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $params);
            //perform our request
            //var_dump($params,$url);die;
            $result = curl_exec($curl_connection);      
            curl_close($curl_connection);  
            return $result;      
        }

        function delete_directory($dirname) {
            if(is_dir($dirname)){
                $dir_handle = @opendir($dirname);

                if (!$dir_handle)
                    return false;
                while($file = readdir($dir_handle)) {
                    if ($file != "." && $file != "..") {
                        if (!is_dir($dirname. DIRECTORY_SEPARATOR .$file))                        
                            unlink($dirname. DIRECTORY_SEPARATOR . $file);
                        else
                            Common::delete_directory($dirname . DIRECTORY_SEPARATOR . $file);    
                    }
                }
                closedir($dir_handle);
                rmdir($dirname);
                return true;
            }   
        }  
        function sanitize_output($buffer)
        {
            mb_internal_encoding('utf-8');
            $search = array(
            '/\>[^\S ]+/s', //strip whitespaces after tags, except space
            '/[^\S ]+\</s', //strip whitespaces before tags, except space
            '/(\s)+/s'  // shorten multiple whitespace sequences
            );
            $replace = array(
            '>',
            '<',
            '\\1'
            );
            $buffer = preg_replace($search, $replace, $buffer);
            $buffer =preg_replace('/\s\s+/','', $buffer);
            $buffer = str_replace("\t",'',$buffer);
            return $buffer;
        }

        static function getRandomArray($rows,$number)
        {
            $results=array();
            $n=count($rows); 
            if($n==0) return $results;
            if($n==1) return $rows;  
            if($n>$number) $n=$number;

            $rand_keys=array_rand($rows,$n);
            if(count($rand_keys)>0 && is_array($rand_keys)){  
                foreach($rand_keys as $key=>$value){
                    $results[]= $rows[$value];
                } 
            } 
            else {
                $results[]=$rows[$rand_keys]; 
            }   
            return $results;    
        }

        static function writeFile($username,$embed_id,$adv){
            $file = Yii::app()->params["path_mtop"]."/".$username."/embed_".$embed_id.".js";   

            //$file = "E:/wamp/www/mtop/wapcontent/shoptv/upload/user/".$username."/js/embed_".$embed_id.".js";   
            //echo $file;die; 
            $content = "";        
            $content .= 'var adv = [';

            $data = "";
            foreach($adv as $i=>$row){
                $data .= ", ['" . mysql_escape_string($row) . "']";
            }
            $data = ltrim($data, ", ");
            $content .= $data;
            $content .= "];";

            $fp = @fopen($file, "w");
            $a = @fwrite($fp, $content);    
            @fclose($fp);
        }

        static function writeFileAdmin($group_id,$adv){
            $file = Yii::app()->params["path_mtop_admin"]."/auto_adv_".$group_id.".js"; 
            unlink($file);
            //$file = "E:/wamp/www/mtop/wapcontent/shoptv/upload/user/".$username."/js/embed_".$embed_id.".js";   
            //echo $file;die; 
            $content = "";        
            $content .= 'var adv = [';

            $data = "";
            foreach($adv as $i=>$row){
                $data .= ", ['" . mysql_escape_string($row) . "']";
            }
            $data = ltrim($data, ", ");
            $content .= $data;
            $content .= "];";

            $fp = @fopen($file, "w");
            @fwrite($fp, $content);      
            @fclose($fp);
        }  

        public function processImageKute($sms_kute_id,$content,$sms,$type=0){
            $padding = 0;  
            Yii::import("application.vendors.SimpleImage",true);
            $location = "/data/website/mtop/mtop.vn/upload/sms_cute/".date("Y")."/".date('m').date('d')."/";                    
            if(@chdir($location) == false) @mkdir($location, 0777, true);
            $padding=0; 
            /*Source image*/
            if($type==0){
                $SourceFile = "/data/website/mtop/mtop.vn/upload/sms_cute/".date('Y').'/'.date('m').date('d')."/".$sms_kute_id.".jpg";
            }else{
                $SourceFile = "/data/website/mtop/mtop.vn/upload/sms_cute/".date('Y').'/'.date('m').date('d')."/".$sms_kute_id."_app.jpg";
            }


            $WaterMarkText = $content."\n".$sms[0]."\n".$sms[1];
            $WaterMarkText = wordwrap($WaterMarkText, 45, "\n", true);

            $text_height=Common::text_height($WaterMarkText);
            $text_width=Common::text_width($WaterMarkText); //180

            $content = wordwrap($content, 45, "\n");  
            $content_height =  Common::text_height($content);
            $arr_content = explode("\n",$content);
            for($i=0;$i<count($arr_content);$i++){
                $arr_content[$i] = str_replace(array("\n","\r\n","\r"), '', $arr_content[$i]);
            }

            Yii::import("application.vendors.SimpleImage",true);       
            $font = dirname(__FILE__) . '/../../themes/ARIALUNI.TTF';
            $font_size = 9;
            //resize anh
            if($content_height < 60){
                $ext_height = 120;
                $ext_sms = 65;
            }else{
                $ext_height = 80;
                $ext_sms = 25; 
            }
            if($type==0){
                $base_width = $text_width + 20; 
                $height_rs = $text_height + $ext_height;   
            }else{           
                $base_width = 214; 
                $height_rs = $text_height + $ext_height;
            }   
            $image = new SimpleImage();
            $filename=Yii::app()->params['static_url'].'images/a3.jpg';
            $image->load($filename);
            $image->resize($base_width,$height_rs);
            $image->save($SourceFile);
            list($width, $height) = getimagesize($SourceFile);

            $image_p = imagecreatetruecolor($width, $height);
            $image = imagecreatefromjpeg($SourceFile);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

            //drawBorder
            $color_red = imagecolorallocate($image_p, 30, 144, 255); 
            //Common::drawBorder($image_p,$color_red,1);
            //Print in black color
            $black = imagecolorallocate($image_p, 0, 0, 0);
            $yellow = imagecolorallocate($image_p, 246, 197, 225);

            foreach($arr_content as $key=>$value){
                $value_width=Common::text_width($value)+$padding + 1; //180   
                $w = $base_width/2 - $value_width/2; 
                imagettftext($image_p, $font_size, 0, $w, 18*($key+1)+$ext_sms+20, $black, $font, $value);
            }
            /*echo $width.'<br/>';
            echo $width/1.6;die; */
            if($type==0){
                foreach($sms as $key=>$value){
                    $sms_width=Common::text_width($value)+$padding; //180   
                    //$sms_height=Common::text_height($value)+$padding; //180   
                    imagefilledrectangle($image_p, 24, $height-22, $width/2.1, $height-8, $yellow);
                    imagefilledrectangle($image_p, 100, $height-22, $width/1.15, $height-8, $yellow); 
                    $w = $base_width/2 -$sms_width/2; 
                    imagettftext($image_p, $font_size, 0, $w, 15*($key+2)+$text_height+$ext_sms, $black, $font, $value);
                }
            }
            $bg = imagecolorallocate($image_p, 255, 255, 255);
            $textcolor = imagecolorallocate($image_p, 30, 144, 255);
            //imagefill($image_p, $width-20, $height-20, $red);
            if ($SourceFile<> "") {
                imagejpeg($image_p, $SourceFile, 100);
            } else {
                header('Content-Type: image/jpeg');
                imagejpeg($image_p, null, 100);
            };
            imagedestroy($image);
            imagedestroy($image_p);
        }

        // function image
        public function watermarkImage($SourceFile, $content,$sms ,$WaterMarkText, $DestinationFile,$type=0) {
            //$SourceFile is source of the image file to be watermarked
            //$WaterMarkText is the text of the watermark
            //$DestinationFile is the destination location where the watermarked images will be placed
            Yii::import("application.vendors.SimpleImage",true);
            //Delete if destinaton file already exists
            @unlink($DestinationFile);
            $padding=0;
            $text_height=Common::text_height($WaterMarkText)+$padding;
            $text_width=Common::text_width($WaterMarkText)+$padding; //180

            //resize anh
            if($type==0){
                $base_width = $text_width; 
                $height_rs = $text_height+80;   
            }else{           
                $base_width = 214; 
                $height_rs = $text_height+20;
            }

            $image = new SimpleImage();
            $filename=Yii::app()->params['static_url'].'images/a3.jpg';
            $image->load($filename);
            $image->resize($base_width,$height_rs);
            $image->save($SourceFile);

            //This is the vertical center of the image
            $top = getimagesize($SourceFile);
            $top = $top[1]/2;
            list($width, $height) = getimagesize($SourceFile);
            $image_p = imagecreatetruecolor($width, $height);
            $image = imagecreatefromjpeg($SourceFile);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

            $font = dirname(__FILE__) . '/../../themes/ARIALUNI.TTF';
            $font_size = 8;
            //drawBorder
            $color_red = imagecolorallocate($image_p, 30, 144, 255); 
            //Common::drawBorder($image_p,$color_red,1);
            //Print in black color
            $black = imagecolorallocate($image_p, 0, 0, 0);
            $yellow = imagecolorallocate($image_p, 246, 197, 225);

            foreach($content as $key=>$value){
                $value_width=Common::text_width($value)+$padding + 1; //180   
                $w = $base_width/2 -$value_width/2; 
                imagettftext($image_p, $font_size, 0, $w, 15*($key+1)+($text_height/7), $black, $font, $value);
            }
            if($type==0){
                foreach($sms as $key=>$value){
                    $sms_width=Common::text_width($value)+$padding; //180   
                    //$sms_height=Common::text_height($value)+$padding; //180   
                    imagefilledrectangle($image_p, $width/8, $height-22, $width/2.1, $height-8, $yellow);
                    imagefilledrectangle($image_p, $width/1.6, $height-22, $width/1.15, $height-8, $yellow); 
                    $w = $base_width/2 -$sms_width/2; 
                    imagettftext($image_p, $font_size, 0, $w, 15*($key+2)+$text_height+25, $black, $font, $value);
                }
            }
            $bg = imagecolorallocate($image_p, 255, 255, 255);
            $textcolor = imagecolorallocate($image_p, 30, 144, 255);
            @unlink($SourceFile);
            //imagefill($image_p, $width-20, $height-20, $red);
            if ($DestinationFile<> "") {
                imagejpeg($image_p, $DestinationFile, 100);
            } else {
                header('Content-Type: image/jpeg');
                imagejpeg($image_p, null, 100);
            };
            imagedestroy($image);
            imagedestroy($image_p);
        }

        /*Lấy độ dài rộng của text nhập vào*/
        public function get_bbox($text){
            $font = dirname(__FILE__) . '/../../themes/ARIALUNI.TTF';    
            return imagettfbbox(10, 0, $font, $text);
        }

        function text_height ($text) {
            $box = Common::get_bbox($text);
            $height = $box[3] - $box[5];
            return $height;
        }

        function text_width ($text) {
            $box = Common::get_bbox($text);
            $width = $box[4] - $box[6];
            return $width;
        }

        function drawBorder(&$im, &$color, $thickness = 1) 
        {   $color_black = ImageColorAllocate($im, 30, 144, 255); 
            $x1 = 0; 
            $y1 = 0; 
            $x2 = ImageSX($im) - 1; 
            $y2 = ImageSY($im) - 1; 

            for($i = 0; $i < $thickness; $i++) 
            { 
                ImageRectangle($im, $x1++, $y1++, $x2--, $y2--, $color_black); 
            } 
        }

        




        
        static function getFilenameGame($user,$filename)//Game online
        {
            return Yii::app()->params['urlImages'].'user/'.$user.'/game/'.$filename;
        }

          

        public function bitly_shorten($url)
        {
            $query = array(
            "version" => "2.0.1"
            , "longUrl"=>$url
            , "login"=>"akaizz"
            , "apiKey"=>"R_8db37d7f5d285377f0a2ce299b2451ad"
            );

            $query = http_build_query($query);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://api.bit.ly/shorten?".$query);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $response = curl_exec($ch);
            curl_close($ch);

            $response = json_decode($response);

            if($response->errorCode == 0 && $response->statusCode == "OK") {
                return $response->results->{$url}->shortUrl;
            } else {
                return null;
            }
        }

        public function decrypt($decrypt, $key=null) 
        {
            $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
            $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($decrypt), MCRYPT_MODE_ECB, $iv);
            return $decrypted;
        }   

        public function encrypt($encrypt, $key=null){          
            $encrypt = trim($encrypt);  
            $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);          
            $len = strlen($encrypt);  
            $padding = $block - ($len % $block);  
            $encrypt .= str_repeat(chr($padding), $padding);    

            $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
            $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $encrypt, MCRYPT_MODE_ECB, $iv);  

            return base64_encode($encrypted);  
        } 

        public function genIdFromLink($group_id,$link){
            switch($group_id){
                case 3:
                    $regx = "/^(\/download-video\/)(\d+)(\/.*)$/si";                           
                    preg_match($regx, $link, $match);
                    break;
                default:
                    $match = array();
                    break;
            }
            $video_id = isset($match[2]) ? $match[2]:0;
            return $video_id; 
        } 
        public function saveFile($data,$upload_path){

            $username = isset($data["username"]) ? trim($data["username"]):"";
            $link_url = isset($data["link_url"]) ? ($data["link_url"]):"";
            $filename = isset($data["filename"]) ? ($data["filename"]):"";

            //$location = getcwd();
            //$upload_path = $location . "/upload/modgame/".$username."/modjar/".date("Y/md",time())."/"; 

            if(@chdir($upload_path) == false){
                @mkdir($upload_path, 0777, true);
                $result = chmod($upload_path, 0777);
                $result = chown($upload_path, "apache"); 
            }
            if($link_url!=""){
                $data =  Common::cUrl($link_url);
                $fp = @fopen($upload_path.$filename, "w");
                @fwrite($fp, $data);                    
                @fclose($fp);
                return 1;
            }else{
                return 0;
            }
        } 
        public function saveFileTmp($data,$upload_path){

            $username = isset($data["username"]) ? trim($data["username"]):"";
            $filename = isset($data["filename"]) ? trim($data["filename"]):"";
            $file = isset($data["file"]) ? ($data["file"]):"";

            //$location = getcwd();
            //$upload_path = $location . "/upload/modgame/".$username."/modjar/".date("Y/md",time())."/"; 
            //echo     $upload_path."tmp </br>";   

            if(@chdir($upload_path) == false){
                @mkdir($upload_path, 0777, true);
                $result = chmod($upload_path, 0777);
                $result = chown($upload_path, "apache"); 
            }
            if($data!=""){
                $fp = @fopen($upload_path.$filename, "w");
                @fwrite($fp, $file);                    
                @fclose($fp);
                return 1;
            }else{
                return 0;
            }
        }
        public function saveLink($data,$upload_path){

            $username = isset($data["username"]) ? trim($data["username"]):"";
            $filename = isset($data["filename"]) ? trim($data["filename"]):"";
            $link_url = isset($data["link_url"]) ? ($data["link_url"]):"";

            //$location = getcwd();
            //$upload_path = $location."/";                    
            //echo     $upload_path."link </br>";        

            if(@chdir($upload_path) == false){
                @mkdir($upload_path, 0777, true);
                $result = chmod($upload_path, 0777);
                $result = chown($upload_path, "apache"); 
            } 

            if($link_url!=""){
                copy($link_url,$upload_path.$filename);
                return 1;
            }else{
                return 0;
            }
        }

    }
?>
